import api from '../api/request.js'

/********
	filePath: 文件路径
	fileType: 文件类型  0:图片 1:视频
	folderName: 指定文件夹名称/路径
	positionType: 存放桶位置 0: clz-hobon-system 系统类  1: clz-hobon-dynamic 动态类
	dateFlag: 是否需要日期 
	deleteFlag: 是否在上传完毕之后删除本地文件
***********/
const uploadFn = async (filePath, fileType, folderName = 'other', positionType = 0, dateFlag = false, deleteFlag =
	true) => {
	//const position = positionType === 0 ? 'clz-hobon-system' : 'clz-hobon-dynamic';
	const result = await api.get('/adm/qiniu/policy', {
		bucket: 'cdp-data-nomal'
	})
	const uploadToken = result.data.token;
	const filename_qn = getFileName(folderName, fileType, dateFlag);
	console.log('filename_qn', filename_qn)
	console.log('uploadToken', uploadToken)
	console.log('filePath', filePath)
	uni.showLoading({
		title: "加载中..."
	})
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: 'https://up-z0.qiniup.com',
			formData: {
				'key': filename_qn, // 存到七牛云后的文件名字，访问图片会用到
				'token': uploadToken, // uploadToken，需要动态获取，调用云函数接口获取
			},
			filePath: filePath,
			name: 'file',
			success: function(res1) {
				uni.hideLoading();
				if (res1.statusCode === 200) {
					const data = JSON.parse(res1.data);
					const url = api.uploadUrlSM + data.key;
					console.log("urlurl", url)
					if (deleteFlag) {
						plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
							entry.remove(function(e) {
								console.log("删除成功");
							}, function(e) {
								console.log("删除失败");
							});
						});
					}
					resolve(url)
				} else {
					uni.showToast({
						icon: "none",
						title: '网络出了点小问题，请稍后再试~'
					})
				}
			}
		})
	})

}

const getDate = () => {
	const now = new Date();
	const month =
		now.getMonth() + 1 < 10 ?
		"0" + (now.getMonth() + 1) :
		now.getMonth() + 1;
	const date = `${now.getFullYear()}${month}${now.getDate() < 10 ? '0' + now.getDate() : now.getDate()}`;
	return date;
}

const getFileName = (folderName = 'other', fileType, dateFlag) => {
	const date = getDate();
	const filename_qn = folderName + (dateFlag ? '/' + date : '') + '/hobon_' + new Date()
		.getTime() + ('000000' + Math.floor(Math.random() * 999999))
		.slice(-6) + (fileType === 0 ? '.jpg' : '.mp4');
	return filename_qn;
}

export default uploadFn;